/*
 * Copyright (C) 2014 luke.
 * 
 * This file is part of Silvie.
 * 
 * Silvie is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Silvie is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Silvie.  If not, see <http://www.gnu.org/licenses/>.
 */

package silvie.gui.previewers;

import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import silvie.gui.Preview;
import utils.DoubleBufferedCanvas;

/**
 * AbstractPreviewer specialization for images.
 * 
 * @author luke
 */
public class ImagePreviewer extends AbstractPreviewer {
	private static final String IMAGE_FILTER_EXTENSION = "png";
	private static final String IMAGE_FILTER_DESCRIPTION = "PNG files (*.png)";
	private Image image;
	private Dimension dimension;

	/**
	 * ImagePreviewer constructor.
	 * 
	 * @param preview the Preview to display on.
	 * @param image the Image to display.
	 */
	public ImagePreviewer(Preview preview, Image image) {
		super(preview);
		this.image = image;
		this.dimension = new Dimension(ImagePreviewer.this.image.getWidth(null), ImagePreviewer.this.image.getHeight(null));
		super.filterDescription = IMAGE_FILTER_DESCRIPTION;
		super.filterExtension = IMAGE_FILTER_EXTENSION;
	}

	@Override
	public void doPreview() {
		Canvas canvas = new DoubleBufferedCanvas() {
			private static final long serialVersionUID = 1L;

			@Override
			public Image getOffscreenImage() {
				return ImagePreviewer.this.image;
			}

			@Override
			public Dimension getPreferredSize() {
				return ImagePreviewer.this.dimension;
			}
		};
		super.preview.setCanvas(canvas, true);
	}

	@Override
	public void close() {}

	@Override
	public File doSave() throws IOException {
		ImageIO.write((RenderedImage) this.image, super.filterExtension, super.savedFile);
		return super.savedFile;
	}
}
